package com.eric.springboot.config.security;

import cn.hutool.core.collection.CollUtil;
import com.eric.springboot.entity.Role;
import com.eric.springboot.entity.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Eric
 * @date 2021.2.2
 */
public class JwtUserDetails implements UserDetails {

    private Long id;

    private String userName;

    private String password;

    private Boolean enable;

    private Collection<? extends GrantedAuthority> authorities;

    public JwtUserDetails(User user) {
        this.id = user.getId();
        this.userName = user.getUserName();
        this.password = user.getPassword();
        this.enable = user.getUsable().equals(1);
        this.authorities = this.getAuthorities(user.getRoles());
    }

    public Long getId() {
        return id;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return authorities;
    }

    @Override
    public String getPassword() {
        return password;
    }

    @Override
    public String getUsername() {
        return userName;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return enable;
    }

    /**
     * 获取角色权限
     *
     * @param roles
     * @return
     */
    private Collection<? extends GrantedAuthority> getAuthorities(List<Role> roles) {
        if (CollUtil.isEmpty(roles)) {
            return null;
        }
        return roles.stream()
                .map(role -> new SimpleGrantedAuthority(role.getName()))
                .collect(Collectors.toList());
    }
}
